<script lang="ts" setup>
import { reactive, ref, watch, type ComponentPublicInstance } from "vue"
import { getListApi, getAmountApi, getRoleAdminCountApi } from "@/api/electron"
import { type FormInstance, type FormRules } from "element-plus"
import { Search, Refresh, RefreshRight } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import ListTable from "./components/listTable.vue"
import History from "./components/history.vue"
import { getAdminRoleListApi } from "@/api/system"

defineOptions({
  // 命名当前组件
  name: "ElementPlus"
})

const star_rating = ref(1)
const HistoryRef = ref<ComponentPublicInstance<InstanceType<typeof History>> | null>(null)

const ListTableRef = ref<ComponentPublicInstance<InstanceType<typeof ListTable>> | null>(null)
const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

//#region 增
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = reactive({
  username: "",
  password: ""
})
const formRules: FormRules = reactive({
  username: [{ required: true, trigger: "blur", message: "请输入用户名" }],
  password: [{ required: true, trigger: "blur", message: "请输入密码" }]
})
// const handleCreate = () => {
//   formRef.value?.validate((valid: boolean, fields) => {
//     if (valid) {
//       if (currentUpdateId.value === undefined) {
//         createTableDataApi(formData)
//           .then(() => {
//             ElMessage.success("新增成功")
//             getTableData()
//           })
//           .finally(() => {
//             dialogVisible.value = false
//           })
//       } else {
//         updateTableDataApi({
//           id: currentUpdateId.value,
//           username: formData.username
//         })
//           .then(() => {
//             ElMessage.success("修改成功")
//             getTableData()
//           })
//           .finally(() => {
//             dialogVisible.value = false
//           })
//       }
//     } else {
//       console.error("表单校验不通过", fields)
//     }
//   })
// }
const resetForm = () => {
  currentUpdateId.value = undefined
  formData.username = ""
  formData.password = ""
}
//#endregion

//#region 删
// const handleDelete = (row: GetTableData) => {
//   ElMessageBox.confirm(`正在删除用户：${row.username}，确认删除？`, "提示", {
//     confirmButtonText: "确定",
//     cancelButtonText: "取消",
//     type: "warning"
//   }).then(() => {
//     deleteTableDataApi(row.id).then(() => {
//       ElMessage.success("删除成功")
//       getTableData()
//     })
//   })
// }
//#endregion

//#region 改
const currentUpdateId = ref<undefined | string>(undefined)
// const handleUpdate = (row: GetTableData) => {
//   currentUpdateId.value = row.id
//   formData.username = row.username
//   dialogVisible.value = true
// }
//#endregion

//#region 查
const tableData = ref<any[]>([])
const listData = ref<any>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  date: "",
  uid: undefined
})
const getTableData = () => {
  loading.value = true
  getListApi({
    date: searchData.date || "",
    uid: searchData.uid || "",
    pageNum: paginationData.currentPage,
    pageSize: paginationData.pageSize
  })
    .then((res) => {
      paginationData.total = res.data.total
      tableData.value = res.data.list
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      getAmountApis()
      loading.value = false
    })
}
const handleSearch = () => {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  searchData.date = ""
  searchData.uid = undefined
  handleSearch()
}
//#endregion

// const pictureFun = (item: any) => {
//   console.log(item)
//   if (ListTableRef.value) {
//     ListTableRef.value?.showClick(item)
//   }
// }

const formatTime = (row: any) => {
  if (!row.update_time) return ""

  const date = new Date(row.update_time)
  // const month = (date.getMonth() + 1).toString().padStart(2, "0")
  // const day = date.getDate().toString().padStart(2, "0")
  const hours = date.getHours().toString().padStart(2, "0")
  const minutes = date.getMinutes().toString().padStart(2, "0")

  return `${hours}:${minutes}`
}
const formatTime2 = (row: any) => {
  if (!row.create_time) return ""

  const date = new Date(row.create_time)
  // const month = (date.getMonth() + 1).toString().padStart(2, "0")
  // const day = date.getDate().toString().padStart(2, "0")
  const hours = date.getHours().toString().padStart(2, "0")
  const minutes = date.getMinutes().toString().padStart(2, "0")

  return `${hours}:${minutes}`
}
const formatTime3 = (row: any) => {
  if (!row.old_create_time) return ""

  const date = new Date(row.old_create_time)
  // const month = (date.getMonth() + 1).toString().padStart(2, "0")
  // const day = date.getDate().toString().padStart(2, "0")
  const hours = date.getHours().toString().padStart(2, "0")
  const minutes = date.getMinutes().toString().padStart(2, "0")

  return `${hours}:${minutes}`
}

const getAdminList = async () => {
  await getAdminRoleListApi({
    role_ids: 2
  })
    .then((res) => {
      listData.value = res.data
    })
    .catch(() => {})
    .finally(() => {})
}
getAdminList()

const amountData = reactive({
  total_quote: 0,
  total_bill: 0
})

const adminStatData = ref<any[]>([])

const getAdminStatData = async () => {
  await getRoleAdminCountApi({
    date: searchData.date || ""
  })
    .then((res) => {
      adminStatData.value = res.data.admin_list || []
    })
    .catch(() => {
      adminStatData.value = []
    })
    .finally(() => {})
}

// 获取进度条颜色
const getProgressColor = (percentage: number) => {
  if (percentage < 30) {
    return "#f56c6c"
  } else if (percentage < 70) {
    return "#e6a23c"
  } else {
    return "#67c23a"
  }
}

const getAmountApis = async () => {
  await getAmountApi({
    date: searchData.date || "",
    uid: searchData.uid || ""
  })
    .then((res) => {
      amountData.total_quote = res.data.total_quote
      amountData.total_bill = res.data.total_bill
      console.log(res)
    })
    .catch(() => {})
    .finally(() => {
      getAdminStatData()
    })
}

//#region
const handleHistorys = (row: any) => {
  console.log("handleHistorys")
  console.log(row)
  if (HistoryRef.value) {
    HistoryRef.value.dialogShow(row)
  }
}
//#endregion

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-row :gutter="20">
        <el-col :span="16">
          <el-form ref="searchFormRef" :inline="true" :model="searchData">
            <el-form-item prop="date" label="查询日期">
              <el-date-picker
                v-model="searchData.date"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                :clearable="true"
                :editable="false"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="业务员">
              <el-select v-model="searchData.uid" placeholder="请选择" clearable>
                <el-option v-for="item in listData" :key="item.id" :label="item.nickname" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
              <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form></el-col
        >
        <el-col :span="8">
          <el-row style="text-align: center">
            <el-col :span="12">
              <div style="color: #909399; font-size: 14px">询价金额</div>
              <div style="font-weight: bold; color: #409eff; font-size: 22px">{{ amountData.total_quote }}</div>
            </el-col>
            <el-col :span="12">
              <div style="color: #909399; font-size: 14px">成交金额</div>
              <div style="font-weight: bold; color: #409eff; font-size: 22px">{{ amountData.total_bill }}</div>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          &nbsp;
          <!-- <el-button type="primary" :icon="CirclePlus" @click="dialogVisible = true">新增用户</el-button> -->
          <!-- <el-button type="danger" :icon="Delete">批量删除</el-button> -->
        </div>
        <div>
          <!-- <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle />
          </el-tooltip> -->
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getTableData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="nickname" label="业务员" align="center" />
          <el-table-column prop="old_create_time" label="创建时间" align="center" :formatter="formatTime3" />
          <el-table-column prop="update_time" label="操作时间" align="center" :formatter="formatTime" />
          <el-table-column prop="totalAmount" label="询价金额" align="center" />
          <el-table-column prop="company_name" label="企业名称" align="center">
            <template #default="{ row }">
              <div v-if="row.company_id != 0">
                <span v-if="row.trade_summary < 20" style="color: red"> 微 </span>
                <span>
                  {{ row.company_name }}
                </span>
                <el-rate v-if="row.star_rating > 1" v-model="star_rating" disabled size="small" :max="1" />
                <el-button key="primary" type="primary" text @click="handleHistorys(row)"> 详情 </el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="total_bill_amount" label="成交金额" align="center" />

          <el-table-column prop="create_time" label="成交时间" align="center" :formatter="formatTime2" />
          <el-table-column prop="interest_rate" label="询价成交比率" align="center" />
          <!-- <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="pictureFun(scope.row)">详情</el-button>
            </template>
          </el-table-column> -->
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <div class="staff-cards-container">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="(item, index) in adminStatData" :key="index">
          <el-card shadow="hover" class="staff-card" v-loading="loading">
            <template #header>
              <div class="staff-card-header">
                <div class="staff-name">{{ item.nickname || "-" }}</div>
                <div class="staff-counts">
                  <div class="count-item">
                    <span class="count-label">询价数量:</span>
                    <span class="count-value">{{ item.count || 0 }}</span>
                  </div>
                  <div class="count-item">
                    <span class="count-label">成交数量:</span>
                    <span class="count-value">{{ item.non_zero_count || 0 }}</span>
                  </div>
                </div>
              </div>
            </template>
            <div class="staff-card-content">
              <el-progress
                type="dashboard"
                :percentage="
                  item.total_amount && parseFloat(item.total_amount) > 0 && item.bill_amount
                    ? Math.round(Math.min((parseFloat(item.bill_amount) / parseFloat(item.total_amount)) * 100, 100))
                    : 0
                "
                :color="getProgressColor"
                :stroke-width="8"
                :width="80"
                class="progress-chart"
              />
              <div class="staff-stat-item">
                <div class="stat-label">询价金额</div>
                <div class="stat-value">{{ item.total_amount || 0 }}</div>
              </div>
              <div class="staff-stat-item">
                <div class="stat-label">成交金额</div>
                <div class="stat-value">{{ item.bill_amount || 0 }}</div>
              </div>
              <div class="staff-stat-item">
                <div class="stat-label">未上传单数</div>
                <div class="stat-value zero-count">{{ item.zero_count || 0 }}</div>
              </div>
              <div class="staff-stat-item">
                <div class="stat-label">询价成交比率</div>
                <div class="stat-value">
                  {{
                    item.total_amount && parseFloat(item.total_amount) > 0 && item.bill_amount
                      ? Math.round((parseFloat(item.bill_amount) / parseFloat(item.total_amount)) * 100)
                      : 0
                  }}%
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="24" v-if="adminStatData.length === 0">
          <el-empty description="暂无数据" />
        </el-col>
      </el-row>
    </div>
    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentUpdateId === undefined ? '新增用户' : '修改用户'"
      @close="resetForm"
      width="30%"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="username" label="用户名">
          <el-input v-model="formData.username" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="password" label="密码" v-if="currentUpdateId === undefined">
          <el-input v-model="formData.password" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <!-- <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button> -->
      </template>
    </el-dialog>
    <ListTable ref="ListTableRef" />
    <History ref="HistoryRef" />
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}

.staff-cards-container {
  margin-top: 20px;
}

.staff-card {
  margin-bottom: 20px;
  transition: all 0.3s;
  position: relative;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);

    .card-actions {
      opacity: 1;
    }
  }

  .staff-card-header {
    display: flex;
    flex-direction: column;
    align-items: flex-start;

    .staff-name {
      font-size: 16px;
      font-weight: bold;
      color: #303133;
      margin-bottom: 8px;
    }

    .staff-counts {
      display: flex;
      width: 100%;
      justify-content: space-between;

      .count-item {
        display: flex;
        align-items: center;

        .count-label {
          font-size: 13px;
          color: #909399;
          margin-right: 4px;
        }

        .count-value {
          font-size: 13px;
          font-weight: bold;
          color: #409eff;
        }
      }
    }
  }

  .staff-card-content {
    display: flex;
    flex-direction: column;
    align-items: center;

    .progress-chart {
      margin-bottom: 15px;
    }

    .staff-stat-item {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;
      padding: 0 10px;

      &:last-child {
        margin-bottom: 0;
      }

      .stat-label {
        color: #909399;
        font-size: 14px;
      }

      .stat-value {
        font-weight: bold;
        color: #409eff;
        font-size: 16px;

        &.zero-count {
          color: #f56c6c;
        }
      }
    }
  }
}
</style>
